package com.lanou.student.util;

import com.lanou.student.bean.User;
import org.apache.poi.ss.usermodel.Row;

import java.lang.reflect.*;

/**
 * @author zyj
 * @date 2022年06月01日 11:49
 */
public class ClassUtil {
    public static <T> T getObj(Row row, Class<T> clazz) {
        //先回获取它的类类型
        T t = null;
        try {
            Constructor<T> constructor = clazz.getConstructor();
            t = constructor.newInstance();
            //获取所有的属性 Field
            Field[] fields = clazz.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Field f = fields[i];
                //set方法的方法名
                String fieldName = f.getName();
                String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                //属性的类类型 Class
                Class fieldClass = f.getType();

                Method method = clazz.getMethod(methodName, fieldClass);
                String parameterValue = row.getCell(i).getStringCellValue();
                if (fieldClass == int.class) {
                    method.invoke(t, Integer.valueOf(parameterValue));
                } else if (fieldClass == double.class){
                    method.invoke(t, Double.valueOf(parameterValue));
                }else {
                    method.invoke(t, parameterValue);
                }

            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return t;
    }


    public static void main(String[] args) {
        System.out.println(getObj(null, User.class));
    }
}
